package com.weibo.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import weibo4j.Count;
import weibo4j.Status;
import weibo4j.User;
import weibo4j.Weibo;
import weibo4j.WeiboException;

import com.weibo.db.DataBaseConnection;
import com.weibo.entity.JianceMail;
import com.weibo.entity.WeiboModel;
import com.weibo.entity.WeiboNeirong;
import com.weibo.entity.WeiboToken;
import com.weibo.util.WeiboHelper;

public class WeiboService extends  DataBaseConnection{
	

	
	/**
	 * 根据转发的语配置微博账号，发布微博
	 * @param id       转发微博ID
	 * @param texts  转发语列表
	 * @param wts    转发的微博
	 * @param isPinglun 是否评论
	 */
	public  void zhuanfa(String id,String texts[],List<WeiboToken> wts , int isPinglun , Long time){
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
    	int i = 0;
    	//有多少个账号转发多少个东西
    	for(WeiboToken wt:wts){
    		Weibo weibo = new Weibo();
    		weibo.setToken(wt.getToken(),wt.getTokenSecret());
    		try {
				weibo.repost(id,texts[i],isPinglun);
				try {
					Thread.sleep(time);//15秒钟一条
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			} catch (WeiboException e) {
				e.printStackTrace();
			}
    		i++;
    	}
	}
	
	public  void piliangfa(List<WeiboToken> wts,String text,String imgURL){
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
    	//有多少个账号发多少个东西
    	for(WeiboToken wt:wts){
    		Weibo weibo = new Weibo();
    		weibo.setToken(wt.getToken(),wt.getTokenSecret());
   
    			try {
					//byte[] content= readFileImage(imgURL);
					//ImageItem pic=new ImageItem("pic",content);
					weibo.updateStatus(text);
					try {
						Thread.sleep(10000);//10秒钟一条
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
				}catch (WeiboException e) {
					e.printStackTrace();
				}
    	}
	
	}
	
	
	
	public void saomiaoPingce(){
		
		String sql1 = "select id from t_weibo";
		ResultSet rs=null;
		try {
			rs = super.getResultSet(sql1, null);
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		List<Integer> ids = new ArrayList<Integer>();
		try {
			while(rs.next()){
				ids.add(rs.getInt("id"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			super.closeAll();
		}
		
		WeiboService ws = new WeiboService();
		for(Integer id : ids){
			ws.saveWeiboNeirongById(id);
			ws.saveWeiboModelById(id);
		}
		
		
		
	}
	
	/**
	 * 根据微博的ID获得新浪微博数据
	 * @param id
	 * @return
	 */
	public void saveWeiboModelById(int id){
		
		java.util.Date date=new java.util.Date();
		Timestamp tt=new Timestamp(date.getTime());
		
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
		Weibo weibo = new Weibo();
		weibo.setToken("656864a57af10603bed431ff5ce00e16","994609030214df396ff1c0ea31009ce8");
		
		User u = null;
		int fensishu = 0;
		 int weiboshu = 0;
		 int zhuanfashu = 0;
		 int pinglunshu = 0;
		 Date saomiaoriqi = null;
		 
		try {
			u = weibo.showUser(id+"");
			fensishu = u.getFollowersCount();
			weiboshu = u.getStatusesCount();
		} catch (WeiboException e1) {
			e1.printStackTrace();
		}
		
		
		
		//System.out.println(time);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		date = calendar.getTime();
		Timestamp tttt1=new Timestamp(date.getTime());
		
		SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
		
		String time = df1.format(date);
		
		//获得转发数和评论数
		String sql1 = "select sum(zhuanfashu)as zf,sum(pinglunshu) as pl from t_weibo_neirong where faburiqi like '%"+time+"%'";
		ResultSet rs=null;
		try {
			rs = super.getResultSet(sql1, null);
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		System.out.println(sql1);
		int zf = 0;
		int pl = 0;
		
		try {
			while(rs.next()){
				zf = rs.getInt("zf");
				pl = rs.getInt("pl");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			super.closeAll();
		}
		
		
		String sql = "insert into t_weibo_pingce(weibo_id,fensishu,weiboshu,saomiaoriqi,zhuanfashu,pinglunshu,weibo_name) " +
				"values('"+id+"','"+fensishu+"','"+weiboshu+"','"+tt+"','"+zf+"','+"+pl+"','"+u.getScreenName()+"')";
		System.out.println("sql:" + sql);
		try {
			super.save(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void saveWeiboNeirongById(int id){
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
		Weibo weibo = new Weibo();
		weibo.setToken("656864a57af10603bed431ff5ce00e16","994609030214df396ff1c0ea31009ce8");
		
		List<Status> ss = null;
			 try {
				ss = weibo.getUserTimeline(id+"");
			} catch (WeiboException e) {
				e.printStackTrace();
			}
			 String ids = "";
			for(Status s : ss){
				ids = ids + s.getId()+",";
			};
			List<Count> cs = null;
			try {
			cs = 	weibo.getCounts(ids);
			} catch (WeiboException e) {
				e.printStackTrace();
			}
			
			
			for(Count c:cs){
				try {
				System.out.println(c.getComments());
				System.out.println(c.getDm());
				System.out.println(c.getId());
				Status status = null;
				try {
					status = weibo.showStatus(c.getId()+"");
				} catch (WeiboException e) {
					e.printStackTrace();
				}
				java.util.Date date=new java.util.Date();
				Timestamp tt=new Timestamp(date.getTime());
				Timestamp ttt=new Timestamp(status.getCreatedAt().getTime());
				String sql = "insert into t_weibo_neirong(weibo_name,weibo_id,id,text,img_url,zhuanfashu,pinglunshu,saomiaoriqi,faburiqi) " +
						"values ('"+status.getUser().getScreenName()+"','"+id+"','"+c.getId()+"','"+status.getText()+"','"+status.getOriginal_pic()+"','"+c.getRt()+"','"+c.getComments()+"','"+tt+"','"+ttt+"')";
				
				
					super.save(sql);
				
				
				} catch (SQLException e) {
					e.printStackTrace();
				}finally{
					super.closeAll();
				}
			}
			
			
	}
	/**
	 * 获得微博的授权码
	 * @return
	 */
	public  List<WeiboToken> findAllToken(){
		String sql = "select * from app_token where appkeyid='3510766076' and zhuangtai='正常'";
		ResultSet rs=null;
		try {
			rs = super.getResultSet(sql, null);
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		List<WeiboToken> list = new ArrayList<WeiboToken>();
		WeiboToken wt = null;
		String app_token = null;
		String token = null;
		try {
		while (rs.next()) {
			wt = new WeiboToken();
			token = rs.getString("token");
			app_token = rs.getString("token_secret");
			if(token != null && app_token != null){
				wt.setToken(token);
				wt.setTokenSecret(app_token);
				wt.setWeiboid(rs.getLong("weiboid"));
				wt.setWeiboname(rs.getString("weiboname"));
				list.add(wt);
			}
		}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}finally{
			super.closeAll();
		}
		
		return list;
	}
	
	/**
	 * 根据微博的id获得微博授权的实体类
	 * @param ids
	 * @return
	 */
	public  List<WeiboToken> findTokenByids(Long ids[]){
		List<WeiboToken>wbts = new ArrayList<WeiboToken>();
		String DriverName ="org.gjt.mm.mysql.Driver";
		String dbURL ="jdbc:mysql://localhost/weibo?useUnicode=true&characterEncoding=utf8";
		String dbuser = "root";
		String dbpassword = "manager";
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			Class.forName(DriverName).newInstance();
			conn = DriverManager.getConnection(dbURL, dbuser, dbpassword);
			stmt = conn.createStatement();
			
			for(int ii = 0; ii < ids.length; ii++){
			String sql = "select * from app_token where appkeyid='3510766076' and weiboid=" + ids[ii];
			rs = stmt.executeQuery(sql);
			String app_token = null;
			String token = null;
			WeiboToken wt = null;
			while (rs.next()) {
				wt = new WeiboToken();
				token = rs.getString("token");
				app_token = rs.getString("token_secret");
				if(token != null && app_token != null){
					wt.setToken(token);
					wt.setTokenSecret(app_token);
					wt.setWeiboid(rs.getLong("weiboid"));
					wt.setWeiboname(rs.getString("weiboname"));
					wt.setFenlei(rs.getString("fenlei"));
					wt.setFensishu(rs.getInt("fensishu"));
					wt.setZhuangtai(rs.getString("zhuangtai"));
					wbts.add(wt);
				}
			}//end for
				
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return wbts;
	}
	public List<Object> yizhouretie(){
		java.util.Date date7=new java.util.Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date7);
		calendar.add(Calendar.DAY_OF_MONTH, -7);
		date7 = calendar.getTime();
		SimpleDateFormat df7 = new SimpleDateFormat("yyyy-MM-dd");
		String time7 = df7.format(date7);//倒退七天
		
		String sql = "select * from t_weibo_neirong where faburiqi>'" + time7 + "' ORDER BY zhuanfashu DESC";
		
		System.out.println(sql);
		ResultSet rs=null;
		try {
			rs = super.getResultSet(sql, null);
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		List<Object> list = new LinkedList<Object>();
		WeiboNeirong wb = null;
		
		try {
			while(rs.next()){
				wb = new WeiboNeirong();
				wb.setWeibo_name(rs.getString("weibo_name"));
				wb.setText(rs.getString("text"));
				wb.setFaburiqi(rs.getDate("faburiqi"));
				wb.setZhuanfashu(rs.getInt("zhuanfashu"));
				wb.setPinglunshu(rs.getInt("pinglunshu"));
				wb.setUrl(WeiboHelper.mid2url(rs.getLong("id")+""));
				list.add(wb);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}finally{
			super.closeAll();
		}
		return list;
		

	}
	
	

	/**
	 * 评测
	 * @return
	 */
	public List<Object>findAll(){
		java.util.Date date7=new java.util.Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date7);
		calendar.add(Calendar.DAY_OF_MONTH, -7);
		date7 = calendar.getTime();
		SimpleDateFormat df7 = new SimpleDateFormat("yyyy-MM-dd");
		String time7 = df7.format(date7);
		
		java.util.Date date1=new java.util.Date();
		Timestamp tt1=new Timestamp(date1.getTime());
		SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
		String time1 = df1.format(date1);
		
		String sql1 = "select * from t_weibo_pingce where saomiaoriqi like '%"+time1+"%'";
		String sql7 = "select * from t_weibo_pingce where saomiaoriqi like '%"+time7+"%'";
		System.out.println(sql1);
		System.out.println(sql7);
		
		ResultSet rs1=null;
		ResultSet rs7=null;
		try {
			rs1 = super.getResultSet(sql1, null);
			rs7 = super.getResultSet(sql7, null);
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		List<WeiboModel> list1 = new ArrayList<WeiboModel>();
		List<WeiboModel> list7 = new ArrayList<WeiboModel>();
		WeiboModel w1 = null;
		WeiboModel w7 = null;
		try {
			while(rs1.next()){
				 w1 = new WeiboModel();
				 w1.setWeibo_id(rs1.getInt("weibo_id"));
				 w1.setFensishu(rs1.getInt("fensishu"));
				 w1.setNicheng(rs1.getString("weibo_name"));
				 w1.setWeiboshu(rs1.getInt("weiboshu"));
				 w1.setZhuanfashu(rs1.getInt("zhuanfashu"));
				 w1.setPinglunshu(rs1.getInt("pinglunshu"));
				 list1.add(w1);
			}
			
			while(rs7.next()){
				System.out.println("执行吗");
				 w7 = new WeiboModel();
				 w7.setWeibo_id(rs7.getInt("weibo_id"));
				 w7.setFensishu(rs7.getInt("fensishu"));
				 w7.setNicheng(rs7.getString("weibo_name"));
				 w7.setWeiboshu(rs7.getInt("weiboshu"));
				 w7.setZhuanfashu(rs7.getInt("zhuanfashu"));
				 w7.setPinglunshu(rs7.getInt("pinglunshu"));
				 list7.add(w7);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}finally{
			super.closeAll();
		}
		
		List<Object> list = new ArrayList<Object>();
		
		int ii1 = list1.size();
		int ii7 = list7.size();
		
		System.out.println(ii1);
		System.out.println(ii7);
		
		for(int i=0;i<ii1; i++){
			WeiboModel wm1 = list1.get(i);
			WeiboModel wm7 = null;
			if(ii7 == ii1){
				wm7 = list7.get(i);
			}
			
			WeiboModel wm = new WeiboModel();
			if(wm1 != null && wm7 != null){
				wm.setId(wm1.getId());
				wm.setNicheng(wm1.getNicheng());
				wm.setFensishu_zong(wm1.getFensishu());
				wm.setWeiboshu_zong(wm1.getWeiboshu());
				wm.setWeiboshu(wm1.getWeiboshu()-wm7.getWeiboshu());
				wm.setFensishu(wm1.getFensishu()-wm7.getFensishu());
				wm.setZhuanfashu(wm1.getZhuanfashu());
				wm.setPinglunshu(wm1.getPinglunshu());
			}

			list.add(wm1);
		}
		
		return list;
	
		
	
		
	}
	
	
	
	
	public static void main(String[] args) {
		WeiboService ws = new WeiboService();
		ws.findAll();

	}

}
